import { User, UserListResponse, TodoListResponse, TodoResponse, TodoCreate, AdminStatsResponse } from '../types/todo'

// API 基础配置
const API_BASE_URL = 'http://localhost:8000'

// 创建一个基础的 fetch 包装函数
async function apiRequest<T>(
  endpoint: string,
  options: RequestInit = {}
): Promise<T> {
  const url = `${API_BASE_URL}${endpoint}`
  
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    ...options.headers as Record<string, string>,
  }
  
  // 添加认证 token
  const token = localStorage.getItem('auth_token')
  if (token) {
    headers.Authorization = `Bearer ${token}`
  }
  
  const config: RequestInit = {
    headers,
    ...options,
  }

  try {
    const response = await fetch(url, config)
    
    if (!response.ok) {
      if (response.status === 401) {
        localStorage.removeItem('auth_token')
        localStorage.removeItem('user_info')
        window.location.reload()
      }
      if (response.status === 403) {
        throw new Error('没有权限访问此资源')
      }
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const data = await response.json()
    return data
  } catch (error) {
    console.error(`API request failed: ${url}`, error)
    throw error
  }
}

// 管理员 API 服务类
export class AdminApiService {
  /**
   * 获取所有用户
   */
  static async getAllUsers(): Promise<UserListResponse> {
    return apiRequest<UserListResponse>('/admin/users')
  }

  /**
   * 获取指定用户的任务
   */
  static async getUserTodos(userId: number): Promise<TodoListResponse> {
    return apiRequest<TodoListResponse>(`/admin/users/${userId}/todos`)
  }

  /**
   * 为用户分配任务
   */
  static async assignTodoToUser(userId: number, todoData: TodoCreate): Promise<TodoResponse> {
    return apiRequest<TodoResponse>(`/admin/users/${userId}/todos`, {
      method: 'POST',
      body: JSON.stringify(todoData),
    })
  }

  /**
   * 删除用户任务
   */
  static async deleteUserTodo(userId: number, todoId: number): Promise<{success: boolean, message: string}> {
    return apiRequest<{success: boolean, message: string}>(`/admin/users/${userId}/todos/${todoId}`, {
      method: 'DELETE',
    })
  }

  /**
   * 获取所有任务（管理员视图）
   */
  static async getAllTodos(): Promise<TodoListResponse> {
    return apiRequest<TodoListResponse>('/admin/todos')
  }

  /**
   * 获取系统统计信息
   */
  static async getStatistics(): Promise<AdminStatsResponse> {
    return apiRequest<AdminStatsResponse>('/admin/statistics')
  }
}

// 导出便捷的 API 方法
export const adminApi = {
  // 用户管理
  getAllUsers: () => AdminApiService.getAllUsers(),
  getUserTodos: (userId: number) => AdminApiService.getUserTodos(userId),
  assignTodo: (userId: number, todoData: TodoCreate) => AdminApiService.assignTodoToUser(userId, todoData),
  deleteTodo: (userId: number, todoId: number) => AdminApiService.deleteUserTodo(userId, todoId),
  
  // 任务管理
  getAllTodos: () => AdminApiService.getAllTodos(),
  
  // 统计信息
  getStats: () => AdminApiService.getStatistics(),
}

// 导出默认实例
export default adminApi